from datetime import datetime

import bcrypt
import pymysql
from flask import jsonify, render_template, request, current_app, abort
from config.config import DB_CONFIG
from werkzeug.utils import secure_filename
import os
from config.config import url
import time


def get_url():
    return url


def get_db_connection():
    return pymysql.connect(**DB_CONFIG)


class Chat:
    def __init__(self, app):
        self.app = app
        self.app.add_url_rule('/api/send_chat', view_func=self.send_chat, methods=['POST'])
        self.app.add_url_rule('/api/get_chat', view_func=self.get_chat, methods=['GET'])

    def send_chat(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        # 从请求中获取currentUser，sellerUser和他们的消息
        data = request.get_json()
        currentUser = data.get('currentUser')
        sellerUser = data.get('sellerUser')
        message1 = data.get('message1')
        message2 = data.get('message2')

        # 创建新的chat记录
        chat_time = datetime.now()
        cursor.execute(
            "INSERT INTO chat (user1, user2, message1, message2, chat_time) VALUES (%s, %s, %s, %s, %s)",
            (currentUser, sellerUser, message1, message2, chat_time)
        )

        # 提交事务
        conn.commit()

        # 关闭数据库连接
        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'msg': '消息已发送'})

    def get_chat(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        # 查询与当前用户有过聊天记录的所有用户
        cursor.execute("SELECT DISTINCT user2 FROM chat WHERE user1 = %s", (username,))
        users = [result[0] for result in cursor.fetchall()]

        # 关闭数据库连接
        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'users': users})